package com.wocai.jrt.orgadmin.news.action;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;

import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.vteba.utils.id.ObjectId;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.vteba.web.editer.StringEditor;
import com.wocai.jrt.orgadmin.employee.model.Org;
import com.wocai.jrt.orgadmin.employee.service.spi.OrgService;
import com.wocai.jrt.orgadmin.news.bean.BasicBean;
import com.wocai.jrt.orgadmin.news.model.News;
import com.wocai.jrt.orgadmin.news.model.NewsBean;
import com.wocai.jrt.orgadmin.news.service.spi.NewsService;
import com.wocai.jrt.orgadmin.utils.ImgType;
import com.wocai.jrt.orgadmin.utils.MyFileUtils;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 新闻控制器
 * 
 * @author yinlei
 * @date 2015-8-10 15:45:28
 */
@Controller
@RequestMapping("/news")
public class NewsAction extends GenericAction<News> {
	private static final Logger LOGGER = LoggerFactory.getLogger(NewsAction.class);

	@Inject
	private NewsService newsServiceImpl;
	@Inject
	private OrgService orgServiceImpl;

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		// 空字符串转换为null
		binder.registerCustomEditor(String.class, new StringEditor());
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(
				"yyyy-MM-dd"), true));
	}

	/**
	 * 获得新闻List，初始化列表页。
	 * 
	 * @param model
	 *            参数
	 * @return 新闻List
	 */
	@RequestMapping("/list")
	public String list(News model, Map<String, Object> maps) {
		try {
			List<News> list = newsServiceImpl.pagedList(model);
			maps.put("list", list);
		} catch (Exception e) {
			LOGGER.error("get record list error, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
		return "news/list";
	}

	@ResponseBody
	@RequestMapping("/query")
	public Map<String, Object> query(@RequestBody BasicBean bean) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			NewsBean newsBean = new NewsBean();
			newsBean.setOrderBy("orders desc");

			NewsBean.Criteria criteria = newsBean.createCriteria();
			if (null != bean.getTitle()) {
				criteria.andTitleLike(bean.getTitle() + "%");
			}
			if (null != bean.getBeginDate()) {
				criteria.andCreateTimeGreaterThanOrEqualTo(bean.getBeginDate());
			}
			if (null != bean.getEndDate()) {
				bean.setEndDate(new DateTime(bean.getEndDate()).plusDays(1).toDate());
				criteria.andCreateTimeLessThan(bean.getEndDate());
			}
			if (0 != bean.getPageSize()) {
				newsBean.setStart(bean.getStart());
				newsBean.setPageSize(bean.getPageSize());
			}
			if (bean.getStatus() != -1) {
				criteria.andStateEqualTo(bean.getStatus());
			}
			if (bean.getPlatform() != 0) {
				criteria.andPlatformEqualTo(bean.getPlatform());
			}
			criteria.andOrgIdEqualTo(UserUtils.getOrgId());

			List<News> list = newsServiceImpl.pagedForList(newsBean);

			// 统计的时候，不需要分页
			newsBean.setStart(null);
			long totalRecord = newsServiceImpl.count(newsBean);

			// jQuery datatable 就是这样的参数，阿西吧
			// result.put("sEcho", user.getEcho());// 这个参数要回传，但是好像也不需要，阿西吧
			result.put("aaData", list); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("news query error, msg=[{}]", e.getMessage());
		}
		return result;
	}

	/**
	 * 根据Id获得新闻实体，Json格式。
	 * 
	 * @param id
	 *            参数id
	 * @return 新闻实体
	 */
	@ResponseBody
	@RequestMapping("/get")
	public News get(String id) {
		News model = null;
		try {
			model = newsServiceImpl.get(id);
		} catch (Exception e) {
			LOGGER.error("get record error, errorMsg=[{}].", e.getMessage());
		}
		return model;
	}

	/**
	 * 跳转到新增页面
	 * 
	 * @return 新增页面逻辑视图
	 */
	@RequestMapping("/add")
	public String add(Map<String, Object> maps) {
		try {
			News news = new News();
			news.setOrderBy("orders desc");
			news.setOrgId(UserUtils.getOrgId());
			List<News> list = newsServiceImpl.pagedList(news);

			int orders = 0;
			if (list != null && list.size() > 0) {
				orders = list.get(0).getOrders() + 1;
			}
			maps.put("orders", orders);
		} catch (Exception e) {
			LOGGER.error("get record list error, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
		return "news/add";
	}

	/**
	 * 执行实际的新增操作
	 * 
	 * @param model
	 *            要新增的数据
	 * @return 新增页面逻辑视图
	 */
	@ResponseBody
	@RequestMapping("/doAdd")
	public JsonBean doAdd(News model) {
		JsonBean bean = new JsonBean();
		try {
			String id = ObjectId.get().toString();
			String orgId = UserUtils.getOrgId();
			model.setId(id);
			if (model.getState()==1) {				
				model.setCreateTime(new Date());
			}
			model.setOrgId(UserUtils.getOrgId());
			Org org = orgServiceImpl.get(orgId);
			model.setSource(org.getBriefName());
			model.setType(1);// 1为图文新闻
			if (model.getVideo() != null) {
				if (model.getVideo().length()>500) {
					bean.setCode(0);
					bean.setMessage("视频分享地址过长！");
					return bean;
				}
				model.setInfo(model.getVideo());// 这个字段留着没用，拿来保存视频
				model.setType(2);// 2为含有视频的新闻
			}
			int result = newsServiceImpl.save(model);
			if (result == 1) {
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				LOGGER.info("save record success.");
				if (model.getState() == 1) {
					// 向机构下所有成员发送最新新闻消息
					newsServiceImpl.createNewsMessage(model);
				}
			} else {
				bean.setMessage(ERROR);
				LOGGER.error("save record error.");
			}
		} catch (Exception e) {
			LOGGER.error("save record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}

	/**
	 * 跳转到编辑信息页面
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 编辑页面
	 */
	@RequestMapping("/edit/{id}")
	public String edit(@PathVariable("id") String id, Map<String, Object> maps) {
		try {
			News model = new News();
			model = newsServiceImpl.get(id);
			maps.put("model", model);
		} catch (Exception e) {
			LOGGER.error("edit record detail, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
		return "news/edit";
	}

	/**
	 * 更新新闻信息
	 * 
	 * @param model
	 *            要更新的新闻信息，含有ID
	 * @return 操作结果信息
	 */
	@ResponseBody
	@RequestMapping("/update")
	public JsonBean update(News model) {
		JsonBean bean = new JsonBean();
		try {
			model.setType(1);// 1为图文新闻
			if (model.getVideo() != null) {
				if (model.getVideo().length()>500) {
					bean.setCode(0);
					bean.setMessage("视频分享地址过长！");
					return bean;
				}
				model.setInfo(model.getVideo());// 这个字段留着没用，拿来保存视频，阿西吧
				model.setType(2);// 2为含有视频的新闻
			}
			if (model.getState() == 0) {
				model.setCreateTime(null);
			}else {
				model.setCreateTime(new Date());
			}
			
			News news = newsServiceImpl.get(model.getId());
			int result = newsServiceImpl.updateById(model);
			if (result == 1) {
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				LOGGER.info("update record success.");
				// 当新闻从未发布状态变为发布状态时发布消息
				if (news.getState() == 0 && model.getState() == 1) {
					// 向机构下所有成员发送最新新闻消息
					newsServiceImpl.createNewsMessage(model);
				}
			} else {
				bean.setMessage(ERROR);
				LOGGER.error("update record error.");
			}
		} catch (Exception e) {
			LOGGER.error("update record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}

	/**
	 * 删除新闻信息
	 * 
	 * @param id
	 *            要删除的新闻ID
	 */
	@ResponseBody
	@RequestMapping("/delete")
	public JsonBean delete(String id) {
		JsonBean bean = new JsonBean();
		try {
			News news = newsServiceImpl.get(id);
			if (news == null) {
				bean.setCode(0);
				bean.setMessage("该新闻不存在");
				return bean;
			}
			File file = new File(news.getThumbnail());
			MyFileUtils.deleteFileDir(file);
			int result = newsServiceImpl.deleteById(id);
			if (result == 1) {
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				LOGGER.info("delete record success, id=[{}].", id);
			} else {
				bean.setMessage(ERROR);
				LOGGER.error("delete record error.");
			}
		} catch (Exception e) {
			LOGGER.error("delete record error, id=[{}], errorMsg=[{}].", id, e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}

	@ResponseBody
	@RequestMapping("/uploadFile")
	public JsonBean uploadFile(MultipartFile file, HttpServletResponse response) {
		JsonBean json = new JsonBean();
		if (file.isEmpty()) {
			json.setCode(0);
			json.setMessage("上传的文件不存在");
		}
		try {
			json.setCode(1);
			json.setData(MyFileUtils.uploadImg(file, ImgType.NEWS));
		} catch (IOException e) {
			json.setCode(0);
			json.setMessage("上传文件出错");
			LOGGER.error("uploadAdsThumbnail error, errorMsg=[{}].", e.getMessage());
		}
		// response.setContentType("text/x-json");
		// OutputStream os = response.getOutputStream();
		// // 将验证码写入输出流
		// os.write();
		// os.flush();
		return json;
	}

	/**
	 * 跳转详情页面页面
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 编辑页面
	 */
	@RequestMapping("/detail/{id}")
	public String detail(@PathVariable("id") String id, Map<String, Object> maps) {
		try {
			News model = new News();
			model = newsServiceImpl.get(id);
			if (model == null) {
				model = new News();
				model.setTitle("没有该新闻！");
				model.setContent("如有疑问，请联系管理员。。。");
				maps.put("model", model);
			}else if (model.getState() == null || model.getState() == 0) {
				model.setTitle("这条新闻已过期！");
				model.setContent("如有疑问，请联系管理员。。。");
				maps.put("model", model);
			}else {
				maps.put("model", model);
			}
		} catch (Exception e) {
			LOGGER.error("edit record detail, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
		return "wap/activity";
	}
}
